package id.co.rho.scoring.cid.server.command.handler.impl;

import java.util.Date;
import org.springframework.context.ApplicationContext;
import id.co.rho.scoring.cid.client.command.impl.TypeModelConfigCommand;
import id.co.rho.scoring.cid.client.command.impl.TypeModelConfigResult;
import id.co.rho.scoring.cid.client.command.impl.TypeModelConfigCommand.CommandType;
import id.co.rho.scoring.cid.domain.TypeModelConfig;
import id.co.rho.scoring.cid.server.command.handler.CommandHandler;
import id.co.rho.scoring.cid.server.service.TypeModelConfigService;
import id.co.rho.scoring.cid.server.util.AppContext;

public class TypeModelConfigCommandHandler implements
		CommandHandler<TypeModelConfigCommand, TypeModelConfigResult> {
	@Override
	public TypeModelConfigResult execute(TypeModelConfigCommand command) {
		ApplicationContext ctx = AppContext.getApplicationContext();
		TypeModelConfigService svc = ctx.getBean(TypeModelConfigService.class);
		Date dateNow = new Date();
		TypeModelConfigResult result = new TypeModelConfigResult();
		if (command.getCommandType() == CommandType.ADD) {
			TypeModelConfig model = new TypeModelConfig();
			model.setCode(command.getCode());
			model.setName(command.getName());
			model.setDescr(command.getDescr());
			model.setCreatedBy(command.getCreatedBy());
			model.setCreatedDate(dateNow);
			TypeModelConfig res = null;
			res = svc.saveOrUpdate(model);
			if (res != null)
				result.setSaved(true);
			else
				result.setSaved(false);
		} else if (command.getCommandType() == CommandType.EDIT) {
			TypeModelConfig model = svc.getTypeModelConfigById(command.getId());
			model.setCode(command.getCode());
			model.setName(command.getName());
			model.setDescr(command.getDescr());
			model.setUpdatedBy(command.getUpdatedBy());
			model.setUpdatedDate(dateNow);
			TypeModelConfig res = null;
			res = svc.saveOrUpdate(model);
			if (res != null)
				result.setSaved(true);
			else
				result.setSaved(false);
		} else if (command.getCommandType() == CommandType.DELETE) {
			TypeModelConfig model = svc.getTypeModelConfigById(command.getId());
			model.setDeletedby(command.getDeletedby());
			model.setDeletedDate(dateNow);
			model.setDeleted(true);
			TypeModelConfig res = null;
			res = svc.saveOrUpdate(model);
			if (res != null)
				result.setSaved(true);
			else
				result.setSaved(false);
		} else if (command.getCommandType() == CommandType.SEARCH) {
			result = svc.searchByCodeAndName(command.getCode(),
					command.getName());
		} else if (command.getCommandType() == CommandType.SEARCH_ALL) {
			result = svc.findAll();
		}
		return result;
	}

	@Override
	public Class<TypeModelConfigCommand> getActionType() {
		return TypeModelConfigCommand.class;
	}

}
